<?php

namespace App\Http\Middleware;

use App\Lib\Code;
use App\Services\ApiResponseService;
use Closure;
use Illuminate\Support\Facades\Auth;

class TradePwdVerify
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $type='trade')
    {
        $key = $type .'_pwd';
        if ( ! $request->has($key)) {
            return $type == 'trade'
                ? ApiResponseService::showError(Code::TRADE_PWD_INVALID)
                : ApiResponseService::showError(Code::LOGIN_PWD_INVALID);
        }
        $pwd = $request->input($key);
        $user = Auth::user();
        $userKey = $type == 'trade' ? 'trade_pwd' : 'password';
        if ( ! password_verify($pwd, $user->$userKey)) {
            return $type == 'trade'
                ? ApiResponseService::showError(Code::TRADE_PWD_INVALID)
                : ApiResponseService::showError(Code::LOGIN_PWD_INVALID);
        }
        return $next($request);
    }
}
